# -*- coding: utf-8 -*-
from MyApi import *
import thosttraderapi as api
import configparser
import time
import re


#config
configins=configparser.ConfigParser()
configins.read('config.ini')
#search conf
SEARCHSEQ=int(configins['searchopt']['searchseq'])
#fileconf read
MDFILE=configins['fileconf']['mdfile']
MDPATH=configins['fileconf']['mdpath']
INSFILE=configins['fileconf']['insfile']
INSPATH=configins['fileconf']['inspath']
#checkexchange
checkexchange=configins['searchopt']['checkexchange'].split(',')

#re
#option instrument search
optinstrre='[a-zA-Z]+[0-9]+-?[C|P]-?[0-9]+'
optinstrpat=re.compile(optinstrre)


def main():
	mddata=[]
	insdata=[]
	mylog.info("start init instance")

	myapi=CTradeApi()

	#login 
	rc = myapi.start()
	rc = myapi.ReqAuth()
	rc = myapi.ReqLogin()

	#md query loop
	while(True):
		insdata = myapi.ReqQryClsIns()
		time.sleep(1)
		mddata = myapi.ReqQryMD()
		rc = SettlePriceCheck(mddata)
		if(rc == True):
			mylog.info("write to csv")
			WriteToCSVins(mddata[0][0], insdata, INSPATH, INSFILE, True)
			WriteToCSV(mddata, MDPATH, MDFILE, True)
			mddata.clear()
			insdata.clear()
			break
		else:
			mylog.info("lake of settleprice,wait for another query")
			WriteToCSVins(mddata[0][0], insdata, INSPATH, INSFILE, False)
			WriteToCSV(mddata, MDPATH, MDFILE, False)
			mddata.clear()
			insdata.clear()
			time.sleep(SEARCHSEQ)


def SettlePriceCheck(mddata):
	#set store list
	instrgrouplist=["SHFEFUT", "SHFEOPT",\
			"INEFUT", "INEOPT", "INESP",\
			"CFFEXFUT", "CFFEXOPT", "CFFEXSP",\
			"DCEFUT", "DCEOPT",\
			"CZCEFUT", "CZCEOPT",\
			"GFEXFUT", "GFEXOPT"]
	exchangelist=["SHFE", "INE", "CFFEX", "CZCE", "DCE", "GFEX"]
	checklist = []
	instrgroup={}
	instrflag={}
	returncode=True

	for groupname in instrgrouplist:
		instrgroup[groupname]=[]
		if("OPT" in  groupname):
			instrflag[groupname]=False
		else:
			instrflag[groupname]=True
	

	for mdlist in mddata:
		if('efp' not in mdlist[1] and 'EFP' not in mdlist[1] and '&' not in mdlist[1]):
			if(mdlist[1] == "CVX"):
				instrgroup["CFFEXSP"].append(mdlist)
				continue
			if('TAS' in mdlist[1]):
				instrgroup["INESP"].append(mdlist)
				continue
			if(re.match(optinstrpat, mdlist[1])):
				instrgroup[mdlist[2] + "OPT"].append(mdlist)
			else:
				instrgroup[mdlist[2] + "FUT"].append(mdlist)
	#fut settle check
	for exchangeid in exchangelist:
		groupname=exchangeid+"FUT"
		for mdlist in instrgroup[groupname]:
			if(mdlist[15] == 0):
				instrflag[groupname]=False
				break
	#opt settle check
	for exchangeid in exchangelist:
		groupname=exchangeid+"OPT"
		for mdlist in instrgroup[groupname]:
			if(mdlist[15] != 0):
				instrflag[groupname]=True
				break
	#check exchange list
	for groupname in instrgrouplist:
		for checkex in checkexchange:
			if(checkex in groupname):
				checklist.append(groupname)
		

	for groupname in checklist:
		mylog.warning(groupname + " " + str(instrflag[groupname]))
		if(instrflag[groupname] == False):
			returncode=False
			return returncode
	return returncode


#write marketdata
def WriteToCSV(mddata, filepath, filename, resultflag):
	tradingday = mddata[0][0]
	daypath = filepath + tradingday
	dayfile = filepath + tradingday + "/" + filename
	tempfile = filepath + filename
	if(resultflag):
		if(os.path.exists(daypath) == False):
			os.mkdir(daypath)
		fh = open(dayfile, mode='w')
	else:
		fh = open(tempfile, mode='w')
	title='"TRADINGDAY","INSTRUMENTID","EXCHANGEID","EXCHANGEINSTID","LASTPRICE","PRESETTLEMENTPRICE","PRECLOSEPRICE","PREOPENINTEREST","OPENPRICE","HIGHESTPRICE","LOWESTPRICE","VOLUME","TURNOVER","OPENINTEREST","CLOSEPRICE","SETTLEMENTPRICE","UPPERLIMITPRICE","LOWERLIMITPRICE","PREDELTA","CURRDELTA","UPDATETIME","UPDATEMILLISEC","ACTIONDAY","BANDINGUPPERPRICE","BANDINGLOWERPRICE"'
	print(title, file=fh)
	for mdlist in mddata:
		if('efp' not in mdlist[1] and 'EFP' not in mdlist[1] and '&' not in mdlist[1]):
			currlist = list(map(lambda x: '"' + str(x) + '"', mdlist))
			print(','.join(currlist), file=fh, end="\r\n")
	fh.close()

def WriteToCSVins(tradingday, insdata, filepath, filename, resultflag):
	daypath = filepath + tradingday
	dayfile = filepath + tradingday + "/" + filename
	tempfile = filepath + filename
	if(resultflag):
		if(os.path.exists(daypath) == False):
			os.mkdir(daypath)
		fh = open(dayfile, mode='w')
	else:
		fh = open(tempfile, mode='w')
	title='"INSTRUMENTID","EXCHANGEID","INSTRUMENTNAME","EXCHANGEINSTID","PRODUCTID","PRODUCTCLASS","DELIVERYYEAR","DELIVERYMONTH","MAXMARKETORDERVOLUME","MINMARKETORDERVOLUME","MAXLIMITORDERVOLUME","MINLIMITORDERVOLUME","VOLUMEMULTIPLE","PRICETICK","CREATEDATE","OPENDATE","EXPIREDATE","STARTDELIVDATE","ENDDELIVDATE","INSTLIFEPHASE","ISTRADING","POSITIONTYPE","POSITIONDATETYPE","LONGMARGINRATIO","SHORTMARGINRATIO","MAXMARGINSIDEALGORITHM","UNDERLYINGINSTRID","STRIKEPRICE","OPTIONSTYPE","UNDERLYINGMULTIPLE","COMBINATIONTYPE"'
	print(title, file=fh)
	for inslist in insdata:
		if(inslist[0] == 'CVX' or str(inslist[20]) == '1'):
			currlist = list(map(lambda x: '"' + str(x) + '"', inslist))
			print(','.join(currlist), file=fh, end="\r\n")
	fh.close()


if __name__ == '__main__':
	main()
